<?

/* --|	ACCOUNT
  Software: Socially
  Version: 1.0
  Contact: http://socially.googlecode.com
  Info: http://socially.googlecode.com
  Support: http://socially.googlecode.com
  --------------------------------------------------------------------------
  Author: goker.cebeci | http://gokercebeci.com
  --------------------------------------------------------------------------
  License: Distributed under the GNU General Public License (GPL)
  http://www.gnu.org/licenses/gpl.html
  This program is distributed in the hope that it will be useful - WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.
  ------------------------------------------------------------------------- */

class account {
    /* -----------------------------------------------------------------------
      SYSTEM FUNCTIONS
      ------------------------------------------------------------------------ */

    private static function _add($a) {
        if (!preg_match('/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+\.[a-z]{2,4}$/', strtolower($a['email'])))
            return common::result(400, _('Please enter a valid email address'), array('email'));
        if (strlen($a['pass']) < 6)
            return common::result(400, _('The password must be min. 6 characters'), array('pass'));
        if ((string) $a['pass'] !== (string) $a['repass'])
            return common::result(400, _('The password and repeat password is not equal'), array('pass', 'repass'));
        $a['pass'] = sha1($a['pass']);
        $fullname = explode(' ', $a['name']);
        $lastname = $fullname[count($fullname) - 1];
        $name = str_replace(' ' . $lastname, '', $a['name']);
        if (!$name || !$lastname || count($fullname) == 1)
            return common::result(400, _('Full name must be min. two words! (eg: John Smith)'), array('name'));
        if ($a['sex'] != 'male' && $a['sex'] != 'female')
            return common::result(400, _('Please select your sex'), array('year'));
        $birthday = ($a['year'] . '-' . $a['month'] . '-' . $a['day']);
        if (!$a['year'] || !$a['month'] || !$a['day'])
            return common::result(400, _('Please select your bitrh date'), array('year'));
        // insert new account
        $r = db::query(sprintf("INSERT INTO `account`
                (`username`, `email`, `code`, `password`, `name`, `lastname`, `sex`, `birthday`, `country`, `region`, `latitude`, `longitude`, `timezone`, `access`, `date`)
                VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, NOW())",
                                $a['email'], $a['email'], self::_code($a['email']), $a['pass'], $name, $lastname, $a['sex'], $birthday, $a['country'], $a['region'], $a['latitude'], $a['longitude'], $a['timezone'], $a['access']));
        if ($r)
            return common::result(600, sprintf(_('%s, Already created an account to this email'), $a['email']), array('email'));
        $ID = db::insertid();
        if ($ID)
            return $ID;
        else
            return common::result(800, _('System error, return ID is null'));
    }

    private static function _set($a) {
        $a['username'] = strtolower($a['username']);
        if ($a['username'] && !preg_match('/^[0-9a-z-]{3,30}$/', $a['username']))
            return common::result(400, _('Please enter a valid username'), array('username'));

        if ($a['email'] && !preg_match('/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+\.[a-z]{2,4}$/', strtolower($a['email'])))
            return common::result(400, _('Please enter a valid email address'), array('email'));
        if ((string) $a['pass'] && (string) $a['repass']) {
            if (strlen($a['pass']) < 6)
                return common::result(400, _('The password must be min. 6 characters'), array('pass'));
            if ((string) $a['pass'] !== (string) $a['repass'])
                return common::result(400, _('The password and repeat password is not equal'), array('pass', 'repass'));
            $a['pass'] = sha1($a['pass']);
        }
        if ($a['name']) {
            $fullname = explode(' ', $a['name']);
            $lastname = $fullname[count($fullname) - 1];
            $name = str_replace(' ' . $lastname, '', $a['name']);
            if (!$name || !$lastname || count($fullname) == 1)
                return common::result(400, _('Full name must be min. two words! (eg: John Smith)'), array('name'));
        }
        if ($a['sex'] && $a['sex'] != 'male' && $a['sex'] != 'female')
            return common::result(400, _('Please select your sex'), array('year'));
        if ($a['year']) {
            if (!$a['month'] || !$a['day'])
                return common::result(400, _('Please select your bitrh date'), array('year'));
            $birthday = ($a['year'] . '-' . $a['month'] . '-' . $a['day']);
        }
        if ($a['email']) {
            $u = db::query(sprintf("SELECT `ID` FROM `account` WHERE `email` = '%s';", $a['email']), true);
            if ($u->ID && $u->ID = !$a['ID'])
                return common::result(600, sprintf(_('%s, Already created a account to this email'), $a['email']), array('email'));
        }
        if ($a['username']) {
            $u = db::query(sprintf("SELECT `ID` FROM `account` WHERE `username` = '%s';", $a['username']), true);
            if ($u->ID && $u->ID = !$a['ID'])
                return common::result(600, sprintf(_('%s, Already used to this username'), $a['username']), array('email'));
        }
        db::query("UPDATE account SET ID=ID"
                        . ($a['username'] ? sprintf(",username = '%s'", $a['username']) : '')
                        . ($a['email'] ? sprintf(",email = '%s'", $a['email']) : '')
                        . ($a['code'] ? sprintf(",code = '%s'", $a['code']) : '')
                        . ($a['repass'] ? sprintf(",password = '%s'", $a['pass']) : '')
                        . ($a['name'] ? sprintf(",name = '%s',lastname = '%s'", $name, $lastname) : '')
                        . ($a['sex'] ? sprintf(",sex = '%s'", $a['sex']) : '')
                        . ($a['year'] ? sprintf(",birthday = '%s'", $birthday) : '')
                        . ($a['country'] ? sprintf(",country = '%s'", $a['country']) : '')
                        . ($a['region'] ? sprintf(",region = '%s'", $a['region']) : '')
                        . ($a['city'] ? sprintf(",city = '%s'", $a['city']) : '')
                        . ($a['latitude'] ? sprintf(",latitude = '%s'", $a['latitude']) : '')
                        . ($a['longitude'] ? sprintf(",longitude = '%s'", $a['longitude']) : '')
                        . ($a['timezone'] ? sprintf(",timezone = '%s'", $a['timezone']) : '')
                        . ($a['language'] ? sprintf(",language = '%s'", $a['language']) : '')
                        . (($a['access'] != 0) ? sprintf(",access = '%d'", $a['access']) : '')
                        . ($a['lastlogin'] ? sprintf(",lastlogin = '%s'", $a['lastlogin']) : '')
                        . ($a['ID'] ? sprintf(" WHERE ID = %d;", $a['ID']) : sprintf(" WHERE code = '%s';", $a['code'])));
        return common::result(200, _('Your info has been changed'));
    }

    private static function _get(array $a) {
        if ($a['list']) {
            $a['limit'] = $a['limit'] ? ($a['limit'] > 50 ? 50 : $a['limit']) : 10;
            $a['page'] = $a['page'] ? $a['page'] : 1;
            $a['access'] = $a['access'] ? $a['access'] : 1;
            $a['search'] = $a['search'] ? sprintf(" AND (" . (count(explode('@', $a['search'])) > 1 ? "email = '%s'" : "CONCAT(name.' '.lastname) LIKE '%%%s%%'") . ")",
            $a['search']) : '';
            $d = db::query('SELECT COUNT(ID) as total FROM account WHERE access <= ' . $a['access'] . $a['search'] . ';', true);
            $d->accounts = db::query('SELECT ID,username,email,name,lastname,sex,birthday,country,region,access,lastlogin,`date` FROM account WHERE access <= ' . $a['access']
                            . $a['search']
                            . ' ORDER BY `name` ASC'
                            . ' LIMIT ' . (($a['page'] - 1) * $a['limit']) . "," . $a['limit'] . ';', true, true);
        } else {
            if (!$a['ID'] && !$a['code'] && !$a['username'] && !$a['email'] && !$a['pass'])
                return common::result(800, _('System error, required parameter is empty'));
            $d = db::query('SELECT ID, code, username, email, name, lastname, sex, birthday, country, region, access, lastlogin,`date` FROM account WHERE 1=1'
                            . ($a['ID'] ? sprintf(" AND ID = %d", $a['ID']) : '')
                            . ($a['code'] ? sprintf(" AND code = '%s'", $a['code']) : '')
                            . ($a['username'] ? sprintf(" AND username = '%s'", $a['username']) : '')
                            . ($a['email'] ? sprintf(" AND email = '%s'", $a['email']) : '')
                            . ($a['pass'] ? sprintf(" AND password = '%s'", sha1($a['pass'])) : '')
                            . ';', true);
            if ($d->ID) {
                $d->fullname = $d->name . ' ' . $d->lastname;
                $d->age = common::age($d->birthday);
                $d->contact->country->code = $d->country;
                $d->contact->country->name = world::country($d->contact->country->code, LOCALE);
                $d->contact->region->code = $d->region;
                $d->contact->region->name = world::region($d->contact->country->code, $d->contact->region->code, LOCALE);
                unset($d->country);
                unset($d->region);
            }
        }
        	
        return $d;
    }

    private static function _del(array $a) {
        db::query(sprintf("DELETE FROM account WHERE ID = %d", $a['ID']));
        return common::result(200, _('Successfully deleted the account'));
    }

    private static function _code($data) {
        return sha1($data . '-' . rand(11111111, 99999999));
    }

    /**
     * CONFIRMATION MAIL
     *
     * @param array $a (ID, name, email, lang)
     * @return result object
     */
    private static function _confirmation(array $a) {
        $lang = $a['lang'] ? $a['lang'] : LANG;
        $code = self::_code($a['ID']);
        $title = _('Confirmation code');
        $data = sprintf(_('
        Hi %s;<br />
        Welcome to %s.
        <p><br />Click the confirmation code below or copy and paste it to your browser\'s
        (firefox, safari, chrome, opera, internet explorer...) adress bar to confirm your account.</p>
        %s
        <p>You can use services after confirming  your account.</p>
        <p><br />The %s team.<br /><br />
        Please do not reply to this message; it was sent from an unmonitored email address.<br />
        This message is a service email related to your use of %s.</p>')
                        , '<strong>' . $a['name'] . '</strong>'
                        , '<strong>' . NAME . '</strong>'
                        , '<p><a style="color: #222; font-weight: bold;" href="http://' . DOMAIN . '/' . $lang . '/account/confirm/' . $code . '">http://' . DOMAIN . '/' . $lang . '/account/confirm/' . $code . '</a></p>'
                        , NAME, NAME);
        if (common::mail($a['name'], $a['email'], $title, $data))
            return $code;
        else
            return false;
    }

    /* -----------------------------------------------------------------------
      PUBLIC FUNCTIONS
      ------------------------------------------------------------------------ */

    public static function set(array $a) {
        if ($a['online']) {
            db::query("INSERT INTO accountOnline (ID, sessionID, status, time, date, IP)
				values (" . UID . ",'" . session_id() . "','online','" . @date('U') . "',NOW(),'" . $_SERVER['REMOTE_ADDR'] . "')
				ON DUPLICATE KEY UPDATE sessionID = '" . session_id() . "', status = 'online',  time = '" . @date('U') . "',
				date = NOW(), IP = '" . $_SERVER['REMOTE_ADDR'] . "';");
            return true;
        }
    }

    public static function get(array $a) {
        $d = self::_get($a);
        return $d;
    }

    public static function getid($username) {
        $d = db::query(sprintf("SELECT ID FROM account WHERE username = '%s' LIMIT 1;", $username), true);
        return $d->ID;
    }

    public static function getusername($ID) {
        $d = db::query(sprintf("SELECT username FROM account WHERE ID = '%d' LIMIT 1;", $ID), true);
        return $d->username;
    }

    /* -----------------------------------------------------------------------
      ADMINISTRATION FUNCTIONS
      ------------------------------------------------------------------------ */

    /**
     * CREATE
     *
     * @param array $a [email,pass,repass,name,sex,day,month,year,country,region]
     * @return unknown
     */
    public static function create(array $a) {
        if (!ADMIN)
            return common::result(600, _('Access denied'));
        // limiting access level
        $a['access'] = $a['access'] > ACCESS ? ACCESS : $a['access'];
        // add new account
        if (self::_add($a))
            return common::result(200, _('Account has been created'));
    }

    /**
     * EDIT
     *
     * @param array $a
     * @return result object
     */
    public static function edit(array $a) {
        if (!ADMIN)
            return common::result(600, _('Access denied'));
        if (!$a['ID'])
            return common::result(800, _('System error, ID is empty'));
        // limiting access level
        $a['access'] = $a['access'] > ACCESS ? ACCESS : $a['access'];
        if (USERNAME == EMAIL)
            $a['username'] = $a['email'];
        if (self::_set($a))
            return common::result(200, _('Account information has been changed'));
        else
            return common::result(800, _('System error, account information has been not changed'));
    }

    /**
     * RESEND CONFIRMATION CODE
     *
     * @param array $ID
     * @return result object
     */
    public static function resend($ID) {
        if (!ADMIN)
            return common::result(600, _('Access denied'));
        if (!$ID)
            return common::result(800, _('System error, ID is empty!'));
        // geting account data by ID
        $u = self::_get(array('ID' => $ID));
        // checking confirm status
        if ($u->access > 0)
            return common::result(400, _('The account is already confirmed!'));
        // sending confirmation email
        $code = self::_confirmation(array('ID' => $u->ID, 'email' => $u->email, 'name' => $u->name, 'lang' => $u->lang));
        if ($code) {
            // seting confirmation code by ID
            self::_set(array('ID' => $u->ID, 'code' => $code));
            return common::result(200, _('The confirmation code has been resended.'));
        } else
            return common::result(800, _('The confirmation code sending is failed, please check mail server settings.'));
    }

    /* -----------------------------------------------------------------------
      MEMBER FUNCTIONS
      ------------------------------------------------------------------------ */

    /**
     * JOIN
     *
     * @param array $a [email,pass,repass,name,sex,day,month,year,captcha]
     * @return unknown
     */
    public static function join(array $a) {
        if (strtolower($a['captcha']) != strtolower(CAPTCHA))
            return common::result(400, _('The security code is not correct'), array('captcha'));
        // detect member location data
        $c = world::ip(IP);
        // merge form data and location data
        $a = array_merge($a, $c);
        // set member default access level [JOINACCESS in /apps/accounts/_conf.php]
        $a['access'] = JOINACCESS;
        // add new account
        $ID = self::_add($a);
        if ($ID) {
            $code = self::_confirmation(array('ID' => $ID, 'email' => $a['email'], 'name' => $a['name']));
            if ($code) {
                self::_set(array('ID' => $ID, 'code' => $code));
                return self::login(array('code' => $code, 'js' => $a['js']));
            } else {
                // delete account record
                self::_del(array('ID' => $ID));
                return common::result(800, _('Confirmation code sending is failed, please try again later'));
            }
        }
    }

    /**
     * CONFIRMATION
     *
     * @param array $a (email)
     * @return result object
     */
    public static function confirmation(array $a) {
        if (!preg_match('/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+\.[a-z]{2,4}$/', strtolower($a['email'])))
            return common::result(400, _('Please enter a valid email address'), array('email'));
        $u = self::_get(array('ID' => UID));
        $code = self::_confirmation(array('ID' => $u->ID, 'email' => $a['email'], 'name' => $u->name, 'lang' => $u->lang));
        if ($code) {
            self::_set(array('ID' => $u->ID, 'code' => $code, 'email' => $a['email']));
            return common::result(200, _('The confirmation code has been resended. Please, check your email account.'));
        } else
            return common::result(800, _('The confirmation code sending is failed, please try again later'));
    }

    /**
     * CONFIRM
     *
     * @param string $code
     * @return integer
     */
    public static function confirm($code) {
        if (!$code)
            return 600;
        $u = self::_get(array('code' => $code));
        if ($u->ID && $u->access < 0) {
            self::_set(array('ID' => $u->ID, 'access' => abs($u->access)));
            self::login(array('code' => $code));
            //$_SESSION['access'] = abs($u->access);
            return 200;
        } elseif ($u->access > 0) {
            self::login(array('code' => $code));
            //$_SESSION['access'] = $u->access;
            return 400;
        } else
            return 600;
    }

    /**
     * LOGIN
     *
     * @param array $a (code, email, pass, captcha)
     * @return return object
     */
    public static function login(array $a) {
        // login attempt check
        if ($_COOKIE['LOGINATTEMPT'] > 3) {
            if (strtolower($a['captcha']) != strtolower(CAPTCHA))
                return common::result(400, _('The security code is not correct'), array('captcha'));
        }
        // checking email or username
        if (!$a['code']) {
            // checking email
            if (!preg_match('/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+\.[a-z]{2,4}$/', strtolower($a['email']))) {
                // checking username
                if (preg_match('/^[0-9a-z.]{2,60}$/', strtolower($a['email']))) {
                    $a['username'] = $a['email'];
                    $a['email'] = null;
                } else
                    return common::result(400, _('Please write a valid email address or username'), array('email'));
            }
            // checking password
            if (!$a['pass'])
                return common::result(400, _('Please write a valid password'), array('pass'));
        }
        // get user information
        //if(($a['email']&&$a['pass'])||($a['username']&&$a['pass'])||$a['code'])
        $u = self::_get($a);
        // checking account and access level
        if (abs($u->access) > 1 && $u->ID) {
            // seting account session data
            $_SESSION['UID'] = $u->ID;
            $_SESSION['email'] = $u->email;
            $_SESSION['access'] = $u->access;
            $_SESSION['username'] = $u->username;
            $_SESSION['name'] = $u->name;
            $_SESSION['lastname'] = $u->lastname;
            $_SESSION['lastlogin'] = $u->lastlogin;
            // changing last login date
            self::_set(array('ID' => $u->ID, 'lastlogin' => @date('Y-m-d H:i:s')));
            // seting SKEY [session key] in cookies for rememeber option
            if ($a['remember'])
                setcookie("SKEY", $u->code, time() + 8640000, '/', DOMAIN);
            // resetting LOGINATTEMPT in cookies
            setcookie("LOGINATTEMPT", 0, time() + 8640000, '/', DOMAIN);
            // set user login information
            // browser javascript capability control
            //if(!$a['js']) $u->location = $a['location'];
            self::ping($u->ID);
            return common::result(200, _('Please wait... You are redirecting...'), null, ($a['location'] ? $a['location'] : ('/' . LANG . '/home')), $a['js']);
        }
        // access denied
        setcookie("SKEY", '0', time() - 3600, '/', DOMAIN);
        setcookie("LOGINATTEMPT", ++$_COOKIE['LOGINATTEMPT'], time() + 8640000, '/', DOMAIN);
        if ($_COOKIE['LOGINATTEMPT'] > 3) {
            // refresh page and show captcha
            return common::result(400, _('Wrong user name or password, please try again.'), array('email', 'pass'), '/' . LANG . '/account/login');
        }
        return common::result(400, _('Wrong user name or password, please try again.'), array('email', 'pass'));
    }

    /**
     * REMEMBER
     *
     * @param string $url
     */
    public static function remember($url) {
        if (!self::login(array('code' => $_COOKIE['SKEY'], 'js' => false, 'location' => $url)))
            self::logout();
    }

    /**
     * LOGOUT
     *
     */
    public static function logout() {
        setcookie("SKEY", '0', time() - 3600, '/', DOMAIN);
        $log = _('Logout') . ' ' . $_SESSION['UID'];
        session_unset();
        common::result(200, $log, null);
        header('location: /');
    }

    /**
     * FORGOT YOUR PASSWORD?
     *
     * @param array $a (email, captcha)
     * @return return object
     */
    public static function forgot(array $a) {
        if (!preg_match('/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+\.[a-z]{2,4}$/', strtolower($a['email'])))
            return common::result(400, _('Please enter a valid email address'), array('email'));
        if (strtolower($a['captcha']) != strtolower(CAPTCHA))
            return common::result(400, _('The security code is not correct'), array('captcha'));
        // get account data by email
        $u = self::_get(array('email' => $a['email']));
        if ($u->ID) {
            $u->code = self::_code($u->ID);
            $title = _('Password recovery');
            $data = sprintf(_('
                Hi %s;<br />
                We have received your password reset request. To reset your password, visit the link below. 
                <p><br />E-mail: %s<br />
                Password reset link: %s
                </p>
                <p>Originating IP address: %s</p>
                <p><br />The %s team.<br /><br />
                Please do not reply to this message; it was sent from an unmonitored email address.<br />
                This message is a service email related to your use of %s.</p>')
                            , '<strong>' . $u->name . '</strong>'
                            , '<strong>' . $u->email . '</strong>'
                            , '<a style="color: #222; font-weight: bold;" href="http://' . DOMAIN . '/' . LANG . '/account/reset/' . $u->code . '">http://' . DOMAIN . '/' . LANG . '/account/reset/' . $u->code . '</a>'
                            , IP, NAME, NAME);
            // sending a password assistance email
            if (common::mail($u->name, $u->email, $title, $data)) {
                // changing confirmation code
                self::_set(array('ID' => $u->ID, 'code' => $u->code));
                return common::result(200, _('We have sent you a password assistance email.'));
            } else
                return common::result(800, _('Password assistance mail sending is failed, please try again later'));
        } else
            return common::result(600, _('This email do not use an account'), array('email'));
    }

    /**
     * RESET PASSWORD
     *
     * @param string $code
     * @return integer
     */
    public static function reset($code) {
        if (!$code)
            return 600;
        // geting account data by code
        $u = self::_get(array('code' => $code));
        // if code has an account
        $u->reset = $u->ID ? 200 : 600;
        return $u;
    }

    /**
     * UPDATE
     *
     * @param array $a
     * @return return object
     */
    public static function update(array $a) {
        if (!GENDER_CHANGE)
            unset($a['gender']);
        $a['ID'] = UID;
        if (!$a['ID']) {
            if (strlen($a['pass']) < 6)
                return common::result(400, _('The password must be min. 6 characters'), array('pass'));
            if ((string) $a['pass'] !== (string) $a['repass'])
                return common::result(400, _('The password and repeat password is not equal'), array('pass', 'repass'));
        }
        if (!$a['ID'] && !$a['code'])
            return common::result(800, _('System error, requered paramater is null'));
        if ($a['email'] && EMAIL != $a['email']) {
            if (self::_confirmation(array('name' => $a['name'], 'email' => $a['email']))) {
                $a['code'] = $code;
                $a['access'] = -ACCESS;
                if (USERNAME == EMAIL)
                    $a['username'] = $a['email'];
            } else
                return common::result(800, _('Confirmation code sending is failed, please try again later'));
        }
        if (self::_set($a)) {
            $u = self::_get(array('ID' => $a['ID']));
            if ($u->ID) {
                $_SESSION['username'] = $u->username;
                $_SESSION['email'] = $u->email;
                $_SESSION['name'] = $u->name;
                $_SESSION['lastname'] = $u->lastname;
                $_SESSION['access'] = $u->access;
                if (EMAIL != $a['email'])
                    return common::result(200, _('Your info has been changed. We has been sended new email confoirmation mail. You must confirm it.'));
                else
                    return common::result(200, _('Your info has been changed.'));
            } else
                return common::result(200, sprintf(_('Your password has been changed. %s click here %s to go to login page.')
                                , '<a href="/' . LANG . '/account/login">', '</a>'));
        }
    }

    public static function ping($ID = null) {
        $ID = $ID ? $ID : UID;
        if (!$ID)
            return false;
        db::query("INSERT INTO accountOnline (ID, sessionID, status, time, date, IP)
                values (" . $ID . ",'" . session_id() . "','online','" . @date('U') . "',NOW(),'" . IP . "')
                ON DUPLICATE KEY UPDATE sessionID = '" . session_id() . "', status = 'online',  time = '" . @date('U') . "',
                date = NOW(), IP = '" . IP . "';");
        return true;
    }

    public static function lastonlines($a) {
        $r = db::query(sprintf("SELECT ID FROM accountOnline ORDER BY `date` DESC LIMIT %d", $a['limit']), true, true);
        foreach ($r as $k => $i) {
            $r[$k] = profile::get(array('ID' => $i->ID));
        }
        return $r;
    }

    public static function status($ID) {
        $r = db::query(sprintf("SELECT `status` FROM accountOnline WHERE ID = %d;", $ID), true);
        return $r->status;
    }

    public static function stat() {
        return cache::get(array('online', 'total'));
    }

    public static function push($a) {
        $d = db::query('SELECT * FROM account;', true, true);
        foreach ($d as $u) {
            @mkdir('db/account/' . $u->ID);
            file_put_contents('db/account/' . $u->ID . '/info.json', json_encode(array(
                        'username' => $u->username,
                        'name' => $u->name,
                        'lastname' => $u->lastname,
                        'birthday' => $u->birthday,
                        'sex' => $u->sex,
                        'country' => $u->countryCode,
                        'region' => $u->regionCode,
                        'lastlogin' => @date('Y-m-d H:i:s')
                    )));
        }
    }

    public static function setting($a) {
        list($app, $name) = explode(',', $a['name']);
        db::query(sprintf("INSERT INTO accountSettings (`ID`,`app`,`name`,`value`) VALUES (%d,'%s','%s','%s')
            ON DUPLICATE KEY UPDATE value = '%s';", UID, $app, $name, $a['value'], $a['value']));
        return common::result(100, _('changed'));
    }

    public static function settings($ID, $edit = false) {
        $s = new stdClass();
        $settings = db::query(sprintf("SELECT * FROM accountSettings WHERE ID = %d;", $ID), true, true);
        if (class_exists('friend'))
            $friend = @friend::check(UID, $ID);
        if ($settings)
            foreach ($settings as $i) {
                $app = $i->app;
                $name = $i->name;
                if (!$edit) {
                    switch ($i->value) {
                        case 'enable':
                        case 'everyone':
                            $value = true;
                            break;
                        case 'members':
                            $value = MEMBER ? true : false;
                            break;
                        case 'friends':
                            $value = $friend == 'friend';
                            break;
                        case 'onlyme':
                            $value = $ID == UID;
                            break;
                        case 'anyone':
                        case 'disable':
                            $value = false;
                            break;
                    }
                    @$s->$app->$name = $value;
                } else
                    $s->$app->$name = $i->value;
            }
        $s->friend = $friend;
        return $s;
    }

    public static function crontab() {
        // UPDATE AND CACHE ONLINE AND TOTAL MEMBERS
        db::query('UPDATE accountOnline SET status = \'offline\' WHERE TIMESTAMPDIFF(MINUTE,date,NOW()) > 4;');
        $r = db::query('SELECT
                        (SELECT COUNT(ID) FROM accountOnline WHERE status <> \'offline\') as online,
                        (SELECT COUNT(ID) FROM account WHERE access > 1) as total;',true);
        cache::set('online',$r->online);
        cache::set('total',$r->total);
    }

    public static function listener() {
        if(!UNCONFIRMED && ACCESS && HASPHOTO) self::ping();
    }

    public static function search() {

    }

    public static function sitemap() {
        
    }

}

?>